package com.wiki.gds.user.provider.modular.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.wiki.gds.base.common.utils.MD5Util;
import com.wiki.gds.base.security.admin.utils.SecurityUtil;
import com.wiki.gds.user.facade.sys.dto.UserDto;
import com.wiki.gds.user.facade.sys.model.User;
import com.wiki.gds.user.facade.sys.model.query.UserQuery;
import com.wiki.gds.user.provider.modular.sys.mapper.UserDao;
import com.wiki.gds.user.provider.modular.sys.service.UserService;
import org.beetl.sql.core.Params;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.db.KeyHolder;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    @Autowired
    SQLManager sqlManager;


    @Transactional
    public Long insert(User user) {
        user.setCreateTime(new Date());
        user.setCreateBy(SecurityUtil.getSecurityUser().getId());
        if(StrUtil.isEmpty(user.getPassword())){
            user.setPassword(MD5Util.getMd5Value("123456"));
        }
        user.setStatus(0);
        KeyHolder keyHolder=userDao.insertReturnKey(user);
        return keyHolder.getLong()>0?keyHolder.getLong():null;
    }

    @Transactional
    public Boolean update(User user) {
        user.setUpdateBy(SecurityUtil.getSecurityUser().getId());
        user.setUpdateTime(new Date());
        Integer rs= userDao.updateTemplateById(user);
        return rs>0?true:false;
    }

    @Override
    public Boolean del(User user) {
        return null;
    }

    @Override
    public User getById(Long id) {
        return userDao.unique(id);
    }

    @Override
    public List<User> getList(Map map) {
        return userDao.all();
    }

    @Override
    public void getPageList(PageQuery query) {
        userDao.templatePage(query);
    }

    @Override
    public Long getCount(User user) {
        return null;
    }

    @Override
    public User getBySelf(User user) {
        Query<User> query = sqlManager.query(User.class);
        return query.andEq("loginname",user.getLoginname()).single();
    }

    @Override
    public Long saveOrUpdate(User user) {
        if(user.getId()!=null){
        return this.update(user)==true?user.getId():null;
        }else {
         return this.insert(user);
        }
    }

    @Override
    public Boolean authUser(Long id, String ids) {
        String[] rids=ids.split(",");
        String sql="delete from sys_user_role where user_id=#id#";
        sqlManager.executeUpdate(sql,Params.ins().add("id",id).map());

        sql="INSERT INTO sys_user_role (user_id,role_id) VALUES ";
        for(int i=0;i<rids.length;i++){
            sql+="("+id+","+rids[i]+")";
            if(i!=rids.length-1){
                sql+=",";
            }
        }
        if(sqlManager.executeUpdate(sql,null)==0){
            return  false;
        }
        return true;
    }

    @Override
    public PageQuery listByDept(UserQuery userQuery) {
        String sql="select @pageTag(){\nd.*,e.simple_name as deptName," +
                "(select GROUP_CONCAT(c.name) from sys_user a join sys_user_role b on a.id=b.user_id join sys_role c on b.role_id=c.id where a.id=d.id) as roleName," +
                "(select GROUP_CONCAT(c.id) from sys_user a join sys_user_role b on a.id=b.user_id join sys_role c on b.role_id=c.id where a.id=d.id) as roleIds " +
                "@}\n from sys_user d left join sys_dept e on d.dept_id=e.id where (d.dept_id=#deptId# or e.pids like CONCAT('%',#deptId#,'%')) and d.status!=-1";
        PageQuery<UserDto> query=  new PageQuery(userQuery.getPage().longValue(),userQuery.getSize().longValue());
        Map params=new HashMap();
        params.put("deptId",userQuery.getDeptId());

        if(StrUtil.isNotEmpty(userQuery.getName())){
            params.put("name",userQuery.getName());
           sql+=" and (d.phone like CONCAT('%',#name#,'%') or d.loginname like CONCAT('%',#name#,'%') or d.name like CONCAT('%',#name#,'%'))";
        }
        if(userQuery.getStartTime()!=null){
            params.put("startTime",userQuery.getStartTime());
            sql+=" and d.create_time >=#startTime#";
        }
        if(userQuery.getEndTime()!=null){
            params.put("endTime",userQuery.getEndTime());
            sql+=" and d.create_time <#endTime#";
        }
        query.setParas(params);
        sqlManager.executePageQuery(sql,UserDto.class,query);
        return query;
    }

    @Override
    @Transactional
    public Boolean delBatch(String ids) {
        Boolean flag=true;
        String sql="UPDATE sys_user set status=-1 where id in("+ids+")";
         Integer rs=   sqlManager.executeUpdate(sql,null);
        if(rs>0){
            //删除sys_user_role关联表
            sql="DELETE FROM sys_user_role WHERE user_id in(#ids#)";
          rs=  sqlManager.executeUpdate(sql,Params.ins().add("ids",ids).map());
            if(rs<0){
                return  false;
            }
        }else {
            return  false;
        }
        return flag;
    }

    @Override
    @Transactional
    public Boolean changeStatus(String ids, Integer type) {
        String sql="UPDATE sys_user set status=#type# where id in("+ids+")";
         Integer rs= sqlManager.executeUpdate(sql,Params.ins().add("type",type).map());
        return rs>0?true:false;
    }

}
